package com.fh.config.security;

import com.alibaba.fastjson2.JSON;
import com.fh.bean.pulc.ResultBody;
import com.fh.utils.anomaly.SpringSecurityException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当用户进行登录的时候 报错了会进行处理
 */
public class CustomAuthenticationFailureHandlerConfig implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 根据不同的异常类型进行不同的处理
        if (exception instanceof SpringSecurityException) {
            // 密码错误的情况
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write(JSON.toJSONString(ResultBody.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, exception.getMessage())));
            return;
        }
        // 密码错误的情况
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(JSON.toJSONString(ResultBody.error(HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage())));

    }
}